﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;
using System.Web.Routing;

namespace VQWEB.administrator.handlers
{
    /// <summary>
    /// Summary description for UploadsHandler
    /// </summary>
    public class UploadsHandler : IHttpHandler, IRouteHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Expires = -1;
            string path_upload = "uploads";
            JavaScriptSerializer JSserializer = new JavaScriptSerializer();
            try
            {

                if (context.Request.Params.AllKeys.Contains("folder_upload"))
                {
                    string folder = context.Request.Form["folder_upload"];
                    CreateFolder(folder);

                    string savepath = PhysicalPath(folder);
                    HttpPostedFile postedFile = context.Request.Files["Filedata"];                    
                    string filename = postedFile.FileName;
                    postedFile.SaveAs(savepath + @"\" + filename);

                    string html = ShowFileByFolder(folder);
                    context.Response.Write(html);
                }

                if (context.Request.Params.AllKeys.Contains("show_file"))
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(ShowFileByFolder(context.Request["show_file"]));
                }

                if (context.Request.Params.AllKeys.Contains("show_folder"))
                {
                    var json = JSserializer.Serialize(GetDirInfo(PhysicalPath(path_upload)));
                    context.Response.ContentType = "application/json";
                    context.Response.Write(json);
                }

                if (context.Request.Params.AllKeys.Contains("folder_add"))
                {
                    CreateFolder(context.Request.Form["folder_add"]);

                    var json = JSserializer.Serialize(GetDirInfo(PhysicalPath(path_upload)));
                    context.Response.ContentType = "application/json";
                    context.Response.Write(json);
                }

                if (context.Request.Params.AllKeys.Contains("deletef"))
                {
                    DeleteFileOrFolder(context.Request.Form["deletef"]);
                    context.Response.Write(ShowFileByFolder(context.Request["select"]));
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("Error: " + ex.Message);
            }
        }




        private string[] GetDirInfo(string Root)
        {

            List<string> list = new List<string>();
            list.Add("uploads");
            string host = HttpRuntime.AppDomainAppPath;
            Action<DirectoryInfo> Recurse = null;
            Recurse = (parent) =>
            {

                var children = parent.GetDirectories();

                for (int i = 0; i < children.Length; i++)
                {
                    string full_path = children[i].FullName;
                    string result = full_path.Replace(host, string.Empty);
                    result = result.Replace("\\", "/");
                    list.Add(result);
                    Recurse(children[i]);
                }


            };
            Recurse(new DirectoryInfo(Root));
            return list.ToArray();
        }

        private string ShowFileByFolder(string path_dir)
        {
            //List<string> collection = new List<string>();
            string html = string.Empty;
            string path_physical = PhysicalPath(path_dir);
            if (Directory.Exists(path_physical))
            {
                html = "<div class=\"row\">";
                string[] collection_files = Directory.GetFiles(path_physical);
                string[] collection_folders = Directory.GetDirectories(path_physical);
                
                string[] collection = collection_folders.Union(collection_files).Distinct().ToArray();
                foreach (string item in collection)
                {
                    string src = VirtualPath(path_dir) + "/" + Path.GetFileName(item);
                    string typeFile = "UNKNOW";
                    string extention = Path.GetExtension(item);

                    if (string.IsNullOrEmpty(extention))
                        typeFile = "FOLDER";
                    if (extention.Equals(".xlsx", StringComparison.InvariantCultureIgnoreCase) | extention.Equals(".xls", StringComparison.InvariantCultureIgnoreCase))
                        typeFile = "EXCEL";
                    if (extention.Equals(".doc", StringComparison.InvariantCultureIgnoreCase) | extention.Equals(".docx", StringComparison.InvariantCultureIgnoreCase))
                        typeFile = "WORD";
                    if (extention.Equals(".txt", StringComparison.InvariantCultureIgnoreCase))
                        typeFile = "TXT";
                    if (extention.Equals(".zip", StringComparison.InvariantCultureIgnoreCase) | extention.Equals(".rar", StringComparison.InvariantCultureIgnoreCase))
                        typeFile = "ZIP";
                    if (extention.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase) | extention.Equals(".gif", StringComparison.InvariantCultureIgnoreCase) | extention.Equals(".png", StringComparison.InvariantCultureIgnoreCase) | extention.Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase))
                        typeFile = "IMG";
                    if (extention.Equals(".mp3", StringComparison.InvariantCultureIgnoreCase) | extention.Equals(".avi", StringComparison.InvariantCultureIgnoreCase) | extention.Equals(".mid", StringComparison.InvariantCultureIgnoreCase))
                        typeFile = "MEDIA";
                    if (extention.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase))
                        typeFile = "PDF";

                    html += "<div class=\"col-sm-2\" style=\"margin-bottom:7px;\" >";
                    html += "<div class=\"thumbnail\">";
                    html += "<input type=\"checkbox\" name=\"urlfiles\" value='" + src + "' class=\"pull-left\" />";
                    html += "<button type=\"button\" class=\"close\"  name='" + src + "' aria-hidden=\"true\">&times;</button>";

                    switch (typeFile)
                    {
                        case "FOLDER":
                            html += "<img src='/administrator/icons/folder.png' alt='" + Path.GetFileName(item) + "' >";
                            break;
                        case "EXCEL":
                            html += "<img src='/administrator/icons/excel.png' alt='" + Path.GetFileName(item) + "' >";
                            break;
                        case "WORD":
                            html += "<img src='/administrator/icons/word.png' alt='" + Path.GetFileName(item) + "' >";
                            break;
                        case "TXT":
                            html += "<img src='/administrator/icons/txt.png' alt='" + Path.GetFileName(item) + "' >";
                            break;
                        case "ZIP":
                            html += "<img src='/administrator/icons/rar.png' alt='" + Path.GetFileName(item) + "' >";
                            break;
                        case "MEDIA":
                            html += "<img src='/administrator/icons/media.png' alt='" + Path.GetFileName(item) + "' >";
                            break;
                        case "IMG":
                            html += "<img style=\"width: 48px; height: 48px\" src=" + src + " alt='" + Path.GetFileName(item) + "'>";
                            break;
                        case "PDF":
                            html += "<img src='/administrator/icons/pdf.png' alt='" + Path.GetFileName(item) + "' >";
                            break;
                        default:
                            html += "<img src='/administrator/icons/unknow.png' alt='" + Path.GetFileName(item) + "'>";
                            break;
                    }
                    if (Path.GetFileName(item).Length > 8)
                        html += "<p>" + Path.GetFileName(item).Substring(0, 8) + "..." + "</p>";
                    else
                        html += "<p>" + Path.GetFileName(item) + "</p>";
                    html += "</div>";

                    html += "</div>";

                }               
                html += "</div>";

            }
            return html;

        }

        private string VirtualPath(string dir)
        {
            string path = string.Empty;
            path = HttpRuntime.AppDomainAppVirtualPath + dir;
            path = path.Replace("\\", "/");
            return path;
        }

        private string PhysicalPath(string dir)
        {
            string path = string.Empty;
            path = HttpRuntime.AppDomainAppPath + dir;
            path = path.Replace("/", "\\");
            return path;
        }

        private void DeleteFileOrFolder(string path)
        {
            string path_physical = PhysicalPath(path);
            FileAttributes attr = File.GetAttributes(path_physical);
            if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
            {
                //Folder

                DirectoryInfo infoF = new DirectoryInfo(path_physical);

                foreach (FileInfo file in infoF.GetFiles())
                {
                    file.Delete();
                }
                foreach (DirectoryInfo dir in infoF.GetDirectories())
                {
                    dir.Delete(true);
                }
                Directory.Delete(path_physical);
            }
            else
            {
                //Files
                File.Delete(path_physical);
            }
        }

        private void CreateFolder(string dir)
        {
            string path_physical = PhysicalPath(dir);
            if (!Directory.Exists(path_physical))
                Directory.CreateDirectory(path_physical);

        }


        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return this;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}